<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
            >导入</el-button
          >
          <el-button size="small" type="danger" @click="exportData"
            >导出</el-button
          >
          <el-button
            icon="plus"
            size="small"
            type="primary"
            @click="showDialog = true"

            >新增员工</el-button
          >
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border v-loading="loading" :data="list">
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column label="头像" align="center">
            <template slot-scope="{ row }">
              <img
                @click="showQrCode(row.staffPhoto)"
                v-imagerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="
                  border-radius: 50%;
                  width: 100px;
                  height: 100px;
                  padding: 10px;
                "
                alt=""
              />
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            sortable=""
            :formatter="formatEmployment"
          />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <!-- 作用域插槽 -->
          <el-table-column
            prop="timeOfEntry"
            label="入职时间"
            sortable=""
            align="center"
          >
            <!-- 格式进行格式化 -->
            <template v-slot="{ row }">{{
              row.timeOfEntry | formatDate
            }}</template>
          </el-table-column>
          <el-table-column
            prop="enableState"
            label="账户状态"
            sortable=""
            align="center"
          >
            <template v-slot="{ row }">
              <el-switch :value="row.enableState === 1"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button
           v-if="checkPermission('er')"
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)"
                >角色</el-button
              >
              <el-button type="text" size="small" @click="delEmployee(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 放置新增组件 -->
    <add-employee :show-dialog.sync="showDialog"></add-employee>
    <el-dialog title="二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
  <!-- 放置角色分配组件 -->
 <assign-role ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>
<script>
import AssignRole from "./components/assign-role.vue";
import QrCode from "qrcode";
import { getEmployeeList, delEmployee } from "@/api/employees";
// 格式化聘用形式  枚举
import EmployeeEnum from "@/api/constant/employees";
import AddEmployee from "./components/add-employee.vue";
import { formatDate } from "@/filters/index";
// import { imagerror } from "@/directives";
export default {
  components: {
    AddEmployee,
    AssignRole,
  },
  data() {
    return {
      list: [], //接收数组
      page: {
        page: 1,
        size: 5,
        total: 0,
        // default: imagerror,
      },
      loading: false, //显示遮罩层
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId:''
      // type: this.$route.query.type,
    };
  },
  created() {
    this.getEmployeeList();
  },
  methods: {
    // 获取员工综合列表
    async getEmployeeList() {
      this.loading = true;
      const { total, rows } = await getEmployeeList(this.page);
      (this.page.total = total), (this.list = rows);
      this.loading = false;
    },
    // 分页改变事件
    changePage(nwePage) {
      this.page.page = nwePage;
      this.getEmployeeList();
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index);
      // row一行de数据 column当前列的配置项  cellValue单元格数据 index每个数据的索引
      // 现象：EmployeeEnum.hireType这个数组 里找（id和单元格数据匹配的（id=cellValue 的对象
      const obj = EmployeeEnum.hireType.find((item) => item.id === cellValue);
      // console.log(obj); //obj有可能找不到
      // return de 就是找到的这个对象的value值
      // return obj.value

      return obj ? obj.value : "未知";
      // 可选链 为了防止对象不存在  使用对象的属性报错 obj?.value===obj&&obj.value
      // return obj?.value
    },
    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm("确定删除该员工吗？");
        // 点击确定
        await delEmployee(id);
        this.getEmployeeList();
        this.$message.success("员工删除成功");
      } catch (error) {
        console.log(error);
      }
    },
    // 实现导出  下载npm install xlsx file-saver -S
    // npm install script-loader -S -D
    // 使用懒加载
    exportData() {
      // 导出数据

      // 定义一个headers
      // rows就是一页纸拿到了所有数据
      // 需要格式化数据 data就是格式化的数据
      const headers = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      // 懒加载
      import("@/vendor/Export2Excel").then(async (excel) => {
        // excel是引入文件的导出对象
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.page.total,
        });
        const data = this.formatJson(rows, headers);
        const multiHeader = [["姓名", "主要信息", "", "", "", "", "部门"]];
        const merges = ["A1:A2", "B1:F2", "G1:G2"];
        excel.export_json_to_excel({
          // 至少需要出入一个空的 data
          // booktype设置导出文件类型
          // forEach和map区别
          header: Object.keys(headers),
          data,
          filename: "人员统计表",
          multiHeader,
          merges,
        });
      });
    },
    // 格式化数据方法  格式化rows  [{}]=>[[]]
    formatJson(rows, headers) {
      return rows.map((item) => {
        // 不能直接拿对象里所有属性导出
        // var arr = []
        // item是一条数据对象  我们需要的是里面个别值
        // val就是mobile  username
        // Object.values(headers)能拿到我们需要的值key
        return Object.keys(headers).map((val) => {
          if (
            headers[val] === "timeOfEntry" ||
            headers[val] === "correctionTime"
          ) {
            return formatDate(item[headers[val]]);
          } else if (headers[val] === "formOfEmployment") {
            const obj1 = EmployeeEnum.hireType.find(
              (obj1) => obj1.id === item[headers[val]]
            );
            return obj1 ? obj1.value : "未知";
          }
          return item[headers[val]];
        });
        // console.log(arr)
        // return arr
      });
      // return
    },
    // 生成二维码
    showQrCode(url) {
      // url存在的情况下 才弹出层
      if (url) {
        this.showCodeDialog = true; // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url); // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        });
      } else {
        this.$message.warning("该用户还未上传头像");
      }
    },
    async editRole(id) {
      await this.$refs.assignRole.getUserDetailById(id); // 父组件调用子组件方法
      this.userId = id;
      this.showRoleDialog = true;
    },
  },
};
</script>
